package com.tiantianyuegou.util;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextUtils;
import android.widget.EditText;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by George on 2016/8/31.
 */
public class SelfUtils {
    /**
     * 手机号码正则表达式
     */
    public static boolean isMobileNO(String mobiles) {
        String telRegex = "[1][3578]\\d{9}";
        if (TextUtils.isEmpty(mobiles))
            return false;
        else
            return mobiles.matches(telRegex);
    }

    /**
     * 邮政编码的正则表达式
     */
    public static boolean isZipCode(String code) {
        String codeRegex = "^[1-9]\\d{5}$";
        if (TextUtils.isEmpty(code)) {
            return false;
        } else {
            return code.matches(codeRegex);
        }
    }

    /**
     * 设置EditText光标位置
     */
    public static void setEditSelection(EditText editText, int selection) {
        CharSequence text = editText.getText();
        // Debug.asserts(text instanceof Spannable);
        if (text instanceof Spannable) {
            Spannable spanText = (Spannable) text;
            Selection.setSelection(spanText, selection);
        }
    }

    /**
     * 获取手机机型
     *
     * @return
     */
    public static String getMobileModel() {
        return android.os.Build.MODEL;
    }

    /**
     * 获取手机当前SDK
     *
     * @return
     */
    public static String getMobileSDK() {
        return android.os.Build.VERSION.SDK;
    }

    /**
     * 获取手机系统版本
     *
     * @return
     */
    public static String getMobileRelease() {
        return android.os.Build.VERSION.RELEASE;
    }

    /**
     * 获取手机联网模式
     */
    public static String getNetType(Context context) {
        // 获取网络连接管理者
        ConnectivityManager connectionManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectionManager.getActiveNetworkInfo();
        return networkInfo.getTypeName();
    }

    /**
     * 解析短信验证码
     */
    public static String getDynamicPassword(String str) {
        // 6是验证码的位数一般为六位
        Pattern continuousNumberPattern = Pattern.compile("(?<![0-9])([0-9]{"
                + 6 + "})(?![0-9])");
        Matcher m = continuousNumberPattern.matcher(str);
        String dynamicPassword = "";
        while (m.find()) {
            System.out.print(m.group());
            dynamicPassword = m.group();
        }
        return dynamicPassword;
    }

    /**
     * 小于10的数字处理
     */
    public static String parseNum(int num) {
        String newNum = "";
        if (num < 10) {
            newNum = "0" + num;
        } else {
            newNum = String.valueOf(num);
        }
        return newNum;
    }

    /**
     * 判断字符串是否含有特殊字符
     */
    public static boolean isConSpeCharacters(String string) {
        if (string.replaceAll("[\u4e00-\u9fa5]*[a-z]*[A-Z]*\\d*-*_*\\s*", "")
                .length() == 0) {
            // 不包含特殊字符
            return false;
        }
        return true;
    }

    /**
     * 检测是否有emoji表情
     *
     * @param source
     * @return
     */
    public static boolean containsEmoji(String source) {
        int len = source.length();
        for (int i = 0; i < len; i++) {
            char codePoint = source.charAt(i);
            if (!isEmojiCharacter(codePoint)) { // 如果不能匹配,则该字符是Emoji表情
                return true;
            }
        }
        return false;
    }

    /**
     * 判断是否是Emoji
     *
     * @param codePoint 比较的单个字符
     * @return
     */
    private static boolean isEmojiCharacter(char codePoint) {
        return (codePoint == 0x0) || (codePoint == 0x9) || (codePoint == 0xA)
                || (codePoint == 0xD)
                || ((codePoint >= 0x20) && (codePoint <= 0xD7FF))
                || ((codePoint >= 0xE000) && (codePoint <= 0xFFFD))
                || ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF));
    }

    public String getMD5(String info) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(info.getBytes("UTF-8"));
            byte[] encryption = md5.digest();

            StringBuffer strBuf = new StringBuffer();
            for (int i = 0; i < encryption.length; i++) {
                if (Integer.toHexString(0xff & encryption[i]).length() == 1) {
                    strBuf.append("0").append(Integer.toHexString(0xff & encryption[i]));
                } else {
                    strBuf.append(Integer.toHexString(0xff & encryption[i]));
                }
            }

            return strBuf.toString();
        } catch (NoSuchAlgorithmException e) {
            return "";
        } catch (UnsupportedEncodingException e) {
            return "";
        }
    }

    /**
     * 时间戳转日期
     *
     * @param sdate
     * @return
     */
    public String getDate(String sdate) {

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
////        Long time=new Long(445555555);
//        String d = format.format(sdate);
//        Date date= null;
//        try {
//            date = format.parse(d);
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }
//        System.out.println("Format To String(Date):"+d);
//        System.out.println("Format To Date:"+date);
//        strDate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);

        return format.format(new Date(Long.parseLong(sdate)));
    }


    /**
     * 判断是否是银行卡号
     * @param cardId
     * @return
     */
    public static boolean checkBankCard(String cardId) {
        char bit = getBankCardCheckCode(cardId
                .substring(0, cardId.length() - 1));
        if (bit == 'N') {
            return false;
        }
        return cardId.charAt(cardId.length() - 1) == bit;

    }

    private static char getBankCardCheckCode(String nonCheckCodeCardId) {
        if (nonCheckCodeCardId == null
                || nonCheckCodeCardId.trim().length() == 0
                || !nonCheckCodeCardId.matches("\\d+")) {
            // 如果传的不是数据返回N
            return 'N';
        }
        char[] chs = nonCheckCodeCardId.trim().toCharArray();
        int luhmSum = 0;
        for (int i = chs.length - 1, j = 0; i >= 0; i--, j++) {
            int k = chs[i] - '0';
            if (j % 2 == 0) {
                k *= 2;
                k = k / 10 + k % 10;
            }
            luhmSum += k;
        }
        return (luhmSum % 10 == 0) ? '0' : (char) ((10 - luhmSum % 10) + '0');
    }
}
